package com.fh.util.web3jsw;

import java.util.List;

import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jService;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.NewAccountIdentifier;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.geth.Geth;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.parity.Parity;

public class Web3jGeth {
	
	private final static String gethClientUrl = "http://192.168.1.3:8545";
	
	/**
	 * 创建用户
	 * @param password
	 * @return
	 */
	public static String newAccount(String password) {
        Admin admin =initAdmin();
        Request<?, NewAccountIdentifier> request = admin.personalNewAccount(password);
        NewAccountIdentifier result = null;
        try {
            result = request.send();
            return result.getAccountId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
    /**
     * 查看所有的账号
     * @return
     */
   public static List<String> getAccountlist() {
    	Web3j web3j = initWeb3j(); // defaults to http://localhost:8545/
		try {
			return web3j.ethAccounts().send().getAccounts();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
   

    /**
     * 初始化web3j普通api调⽤用
     *
     * @return web3j
     */
    public static Web3j initWeb3j() {
        return Web3j.build(getService());
    }



    /**
     * 通过http连接到geth节点
     *
     * @return
     */
    public static HttpService getService() {
        return new HttpService(gethClientUrl);
    }


    /**
     * 初始化admin级别操作的对象
     *
     * @return Admin
     */
    public static Admin initAdmin() {
        return Admin.build(getService());
    }
	
}
